/**
 * 邀请码服务
 */

const Logger = require('../utils/logger')
const Validator = require('../utils/validator')
const Generator = require('../utils/generator')

class InviteService {
  constructor(inviteRepo, userRepo) {
    this.inviteRepo = inviteRepo
    this.userRepo = userRepo
  }

  /**
   * 验证邀请码
   */
  async validateInviteCode(code) {
    Logger.info('InviteService', '开始验证邀请码', { code })

    // 参数验证
    Validator.validateInviteCode(code)

    // 查询邀请码
    const inviteCode = await this.inviteRepo.findByCode(code)
    if (!inviteCode) {
      throw new Error('邀请码不存在')
    }

    // 检查状态
    if (inviteCode.status !== 'active') {
      throw new Error('邀请码已失效')
    }

    Logger.info('InviteService', '邀请码验证成功', { 
      code, 
      rewardPoints: inviteCode.rewardPoints 
    })

    return inviteCode
  }

  /**
   * 使用邀请码（注册时调用）
   */
  async useInviteCode(code, userId, phone) {
    Logger.info('InviteService', '使用邀请码', { code, userId, phone })

    // 验证邀请码
    const inviteCode = await this.validateInviteCode(code)

    // 检查该手机号是否已使用过邀请码
    const hasUsed = await this.inviteRepo.hasUsedInviteCode(phone)
    if (hasUsed) {
      throw new Error('该手机号已使用过邀请码')
    }

    // 创建邀请记录
    const recordData = {
      inviteCode: code,
      userId: userId,
      phone: phone,
      rewardPoints: inviteCode.rewardPoints,
      createTime: new Date()
    }
    await this.inviteRepo.createInviteRecord(recordData)

    // 更新邀请码使用次数
    await this.inviteRepo.incrementUsedCount(inviteCode._id)

    // 为用户添加积分
    await this.userRepo.updatePoints(userId, inviteCode.rewardPoints)

    Logger.info('InviteService', '邀请码使用成功', {
      code,
      userId,
      rewardPoints: inviteCode.rewardPoints
    })

    return inviteCode.rewardPoints
  }

  /**
   * 创建邀请码（管理员功能）
   */
  async createInviteCode(rewardPoints, creatorId, remark = '') {
    Logger.info('InviteService', '创建邀请码', { rewardPoints, creatorId })

    // 生成唯一邀请码
    let code
    let exists = true
    let attempts = 0
    
    while (exists && attempts < 10) {
      code = Generator.generateInviteCode()
      const existing = await this.inviteRepo.findByCode(code)
      exists = !!existing
      attempts++
    }

    if (exists) {
      throw new Error('生成邀请码失败，请重试')
    }

    // 创建邀请码
    const inviteData = {
      code: code,
      rewardPoints: rewardPoints,
      status: 'active',
      createTime: new Date(),
      creatorId: creatorId,
      usedCount: 0,
      remark: remark
    }

    const inviteCodeId = await this.inviteRepo.createInviteCode(inviteData)

    Logger.info('InviteService', '邀请码创建成功', { code, inviteCodeId })

    return { code, inviteCodeId }
  }

  /**
   * 禁用邀请码
   */
  async disableInviteCode(code) {
    Logger.info('InviteService', '禁用邀请码', { code })

    const inviteCode = await this.inviteRepo.findByCode(code)
    if (!inviteCode) {
      throw new Error('邀请码不存在')
    }

    await this.inviteRepo.updateStatus(inviteCode._id, 'disabled')

    Logger.info('InviteService', '邀请码已禁用', { code })
    return true
  }
}

module.exports = InviteService

